package com.keydom.ropeskipping.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryption {

    private static final String ALGORITHM = "AES";
    private static final String MODE = "AES/CBC/PKCS5Padding";
    public static final String ENCRYPTION_KEY = "UMbPB7fQWDmK2wZ9"; // Needs to be 16, 24, or 32 bytes long
    public static final String INIT_VECTOR = "2293936313929652"; // Needs to be 16 bytes long

    public static String encrypt(String plainText) throws Exception {
        SecretKeySpec keySpec = generateKey();
        Cipher cipher = Cipher.getInstance(MODE);
        IvParameterSpec ivSpec = new IvParameterSpec(INIT_VECTOR.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText) throws Exception {
        SecretKeySpec keySpec = generateKey();
        Cipher cipher = Cipher.getInstance(MODE);
        IvParameterSpec ivSpec = new IvParameterSpec(INIT_VECTOR.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText.getBytes());
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, "UTF-8");
    }

    private static SecretKeySpec generateKey() throws Exception {
        byte[] key = ENCRYPTION_KEY.getBytes("UTF-8");
        return new SecretKeySpec(key, ALGORITHM);
    }
}
